package com.garlic.face.jlf.ui;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.garlic.face.jlf.App;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.presenter.PayFailContract;
import com.garlic.face.jlf.presenter.PayFailPresenter;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.ServiceInterface;
import com.garlic.face.jlf.transaction.constances.CommonConstant;
import com.garlic.face.jlf.transaction.constances.JLFConstant;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.PrintUtil;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;
import com.printer.sdk.PrinterConstants;
import com.printsdk.usbsdk.UsbDriver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * @author wenhui02.liu
 * @date 2018/8/9.
 */

public class PayFailActivity extends BaseActivity implements PayFailContract.View {
    private static final String TAG = "PayFailActivity";
    private CountDownTimer mCountDownTimer;

    private Button mBtnRetry;

    private ImageView mShopBrand;

    private String mErrorMessage = "";

    PayFailContract.Presenter mPresenter;
    private SuperVisorConfirmDialog supervisorLoginDialog;

    private static UsbDriver mUsbDriver;
    private static UsbDevice mUSBDevice;
    private ArrayList<UsbDevice> deviceList;
    private MyHandler myHandler = new MyHandler(this);
    public static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";

    private static class MyHandler extends Handler {
        private WeakReference<PayFailActivity> mLogActivityWeak;

        public MyHandler(PayFailActivity printLogActivity) {
            mLogActivityWeak = new WeakReference<>(printLogActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PrinterConstants.Connect.SUCCESS:
                    String connectOk = "USB打印机-连接成功";
                    LogUtils.d(TAG + connectOk, true);
                    mLogActivityWeak.get().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String x = PrintUtil.printjlf(getmUSBDevice(), getmUsbDriver());
                            if (TextUtils.isEmpty(x)) {
//                                mLogActivityWeak.get().findViewById(R.id.reprint).setVisibility(View.GONE);
                            } else {
//                                mLogActivityWeak.get().findViewById(R.id.reprint).setVisibility(View.VISIBLE);
                                ToastUtils.toastShow(x, ToastUtils.ERROR);
                            }
                        }
                    });
                    break;
                case PrinterConstants.Connect.FAILED:
                    String connectFaile = "USB打印机-连接失败";
                    ToastUtils.toastShow(connectFaile, ToastUtils.ERROR);
                    LogUtils.e(TAG + connectFaile);
                    break;
                case PrinterConstants.Connect.CLOSED:
                    String connectClose = "USB打印机-连接关闭";
                    ToastUtils.toastShow(connectClose, ToastUtils.INFO);
                    LogUtils.e(TAG + connectClose);
                    break;
                case PrinterConstants.Connect.NODEVICE:
                    String connectNo = "USB打印机-没有连接";
                    ToastUtils.toastShow(connectNo, ToastUtils.ERROR);
                    LogUtils.e(TAG + connectNo);
                    break;
                case CommonConstant.NET_STATE_UNCONNECT:
                    String netStateUnconnect = "网络错误";
                    ToastUtils.toastShow(netStateUnconnect, ToastUtils.ERROR);
                    LogUtils.e(TAG + netStateUnconnect);
                    break;
                default:
                    break;
            }
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_fail_activity);
        mPresenter = new PayFailPresenter(this);
        EventBus.getDefault().register(this);
        double count = Means.getInstance().getRec_Tran().getCount();
        TextView number = (TextView) findViewById(R.id.number);
        String textStr = String.format(getResources().getString(R.string.total_goods_number),(int)count);
//        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(tv);
//        stringBuilder.setSpan(new AbsoluteSizeSpan(ScreenUtils.sp2px(PayFailActivity.this, 20)), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        stringBuilder.setSpan(new ForegroundColorSpan(this.getResources().getColor(R.color.gray_color)), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        stringBuilder.setSpan(new AbsoluteSizeSpan(ScreenUtils.sp2px(PayFailActivity.this, 20)), tv.length() - 3, tv.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        stringBuilder.setSpan(new ForegroundColorSpan(this.getResources().getColor(R.color.gray_color)), tv.length() - 3, tv.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        number.setText(textStr);

        TextView price = (TextView) findViewById(R.id.price);
        double priceN = Means.getInstance().getRec_Tran().getAmount();
        price.setText("¥" + Tools.getFormatNumber(priceN));


        mShopBrand = (ImageView) findViewById(R.id.title_img);
        mShopBrand.setImageDrawable(this.getResources().getDrawable(R.mipmap.jlf_logo));

        mBtnRetry = (Button) findViewById(R.id.retry);
        mBtnRetry.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                destroyTimer();
                finish();
            }
        });
        if (getIntent() != null) {
            mErrorMessage = getIntent().getStringExtra("error_message");
            if (TextUtils.isEmpty(mErrorMessage)) {
                mErrorMessage = "支付失败";
            }
            TextView errorHint = (TextView) findViewById(R.id.error_hint);
            errorHint.setText(mErrorMessage);
        }

        if(getIntent().getStringExtra("action_type").equals(JLFConstant.SCO_PARTIAL_PAY_PSV)){
            //部分支付
            mBtnRetry = (Button) findViewById(R.id.retry);
            mBtnRetry.setText("部分支付联系助理员工");
            mBtnRetry.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showSuperLoginDialog();
                }
            });
        }else {
            mBtnRetry = (Button) findViewById(R.id.retry);
            mBtnRetry.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    destroyTimer();
                    finish();
                }
            });

            mCountDownTimer = new CountDownTimer(30 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    String s = String.format(getResources().getString(R.string.retry_pay), (int)millisUntilFinished / 1000);
                    mBtnRetry.setText(s);
                }

                @Override
                public void onFinish() {
                    mPresenter.cancelOrder("支付错误页面取消交易[自动][" + mErrorMessage + "]");
                }
            }.start();
        }
        App.playSound(getResources().getString(R.string.sound_pay_failed));
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyTimer();
        EventBus.getDefault().unregister(this);
        App.getSoundMgr().stopPlay();
    }

    @Override
    public void destroyTimer() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @Override
    public void gotoMain() {
        App.clearToMainActivity();
    }

    @Override
    public void printText() {
        Message msg = new Message();
        msg.what = PrinterConstants.Connect.SUCCESS;
        myHandler.sendMessageDelayed(msg, 20);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveResponse(JSONObject jsonObject) {
        LogUtils.d("取消交易" + jsonObject.toString(), true);
        mPresenter.parseJson(jsonObject);
    }

    private void showSuperLoginDialog() {
        supervisorLoginDialog = new SuperVisorConfirmDialog(this);
        supervisorLoginDialog.setCallBack(new SuperVisorConfirmDialog.CallBack() {
            @Override
            public void close(View view) {
                supervisorLoginDialog.dismiss();
            }

            @Override
            public void done(String account, String psw) {
                supervisorLoginDialog.dismiss();
                showProgress();
                ServiceInterface.getInstance().superVisor(account, psw, JLFConstant.SCO_PARTIAL_PAY_PSV);
            }

            @Override
            public void finish(String account_psw) {
                Log.e(TAG,"account_psw:"+account_psw);
                if(TextUtils.isEmpty(account_psw) || !account_psw.contains("&")){
                    ToastUtils.toastShow("请扫描合法的助理员工授权码", ToastUtils.ERROR);
                    return;
                }

                String date = account_psw.substring(0, account_psw.indexOf("&"));
                String account = account_psw.substring(account_psw.indexOf("&") + 1, account_psw.indexOf("-"));
                String psw = account_psw.substring(account_psw.indexOf("-") + 1, account_psw.length());
                supervisorLoginDialog.dismiss();
                if(!checkTimeLegal(date)){
                    ToastUtils.toastShow("二维码已过期", ToastUtils.ERROR);
                }else {
                    showProgress();
                    ServiceInterface.getInstance().superVisor(account, psw, JLFConstant.SCO_PARTIAL_PAY_PSV);
                }
            }
        });
        supervisorLoginDialog.show();
    }

    private boolean checkTimeLegal(String time){
        boolean legal = false;
        long currentTime = new Date().getTime();

        long printTime = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        try {
            Date date = format.parse(time);
            printTime = date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Log.e("---------time", currentTime + "---" + printTime);
        if(((currentTime - printTime) < (24* 3600000))){
            legal = true;
        }

        return legal;
    }

    private void init() {
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        usbAutoConn(manager);
    }

    /**
     * 打开自动连接打印机
     *
     * @param manager
     */
    public void usbAutoConn(UsbManager manager) {
        doDiscovery(manager);
        if (deviceList.isEmpty()) {
            ToastUtils.toastShow("USB打印机没有连接", ToastUtils.ERROR);
            return;
        }
        mUSBDevice = deviceList.get(0);
        if (mUSBDevice == null) {
            String connectFaile = "USE打印机-连接失败";
            LogUtils.e(TAG + connectFaile);
            ToastUtils.toastShow(connectFaile, ToastUtils.ERROR);
            return;
        }
        // 美松
        mUsbDriver = new UsbDriver(manager, this);
        LogUtils.d("deviceName: " + mUSBDevice.getDeviceName(), true);

        UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        try {
            if (mUsbManager != null) {
                if (mUsbManager.hasPermission(mUSBDevice)) {
                    openUsbConnect();
                } else {
                    // 没有权限询问用户是否授予权限
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
                    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
                    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                    registerReceiver(mUsbReceiver, filter);
                    mUsbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后，系统弹出一个对话框
                }
            } else {
                String msg = "USBManager空指针";
                LogUtils.e(TAG + msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "USB-Service空指针";
            LogUtils.e(TAG + msg);
        }
    }

    /**
     * 打开USB打印机
     */
    private void openUsbConnect() {
        mUsbDriver.usbAttached(mUSBDevice);
        boolean b = mUsbDriver.openUsbDevice(mUSBDevice);
        if (b) {

        }
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    unregisterReceiver(mUsbReceiver);
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                            && mUSBDevice.equals(device)) {
                        openUsbConnect();
                    } else {
                        myHandler.obtainMessage(PrinterConstants.Connect.FAILED).sendToTarget();
                    }
                }
            }
        }
    };

    /**
     * 没有则自动获取设备
     *
     * @param manager
     */
    private void doDiscovery(UsbManager manager) {
        HashMap<String, UsbDevice> devices = manager.getDeviceList();
        deviceList = new ArrayList<UsbDevice>();
        for (UsbDevice device : devices.values()) {
            if (PrintUtil.isUsbPrinter(device)) {
                LogUtils.d(TAG + "doDiscovery: " + device.getDeviceName(), true);
                deviceList.add(device);
            }
//            if (USBPort.isUsbPrinter(device)) {
//                deviceList.add(device);
//            }
        }
    }

    public static UsbDevice getmUSBDevice() {
        return mUSBDevice;
    }
    public static UsbDriver getmUsbDriver() {
        return mUsbDriver;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK ) {
            //do something.
            return true;
        }else {
            return super.dispatchKeyEvent(event);
        }
    }
}
